<?php

namespace controller\blog;

class blog
{
    public $data;

    public function __construct()
    {
        $site_info = uuu_all_cfg(28);
        $this->data = [
            'title' => $site_info['博客名称'],
            'theme_id' => $site_info['主题'],
            'description' => $site_info['博客简介'],
            'blogprofile' => $site_info['博客图片'],
            'copyright' => $site_info['版权说明'],
            'show_article_guestbook' => $site_info['显示留言'],
            'open_article_guestbook' => $site_info['开启留言'],
            'current' => "",
            'err' => "",
            'w' => ""
        ];
    }

    public function home()
    {
        $one_page_count = 10;
        $now_page = getGet('page');
        if (!$now_page) {
            $now_page = 1;
        }
        $this->data['current'] = 'home';
        $this->data['container'] = qqq_select_artlist(27, ['pagesize' => $one_page_count, 'page' => $now_page], true);
        $this->data['pager'] = pager_full(
            M()->select_count('articles', 'where ison=1'),
            $now_page,
            $one_page_count,
            3,
            '<<',
            '>>',
            '<a class="{active} nav-link-next nav-item nav-link rounded" href="/blog/list-{page}.html">{text}</a>',
            '<a class="{disabled} {active} nav-link-next nav-item nav-link rounded"  href="/blog/list-{page}.html">上一页</a>',
            '<a class="{disabled} {active} nav-link-next nav-item nav-link rounded"  href="/blog/list-{page}.html">下一页</a>'
        );
        echo view_plates()->render('blog/home', $this->data);
    }

    public function about()
    {
        $this->data['current'] = 'about';
        $this->data['container'] = qqq_one_cfg('内容', 24);
        echo view_plates()->render('blog/page', $this->data);
    }

    public function search($w = '')
    {
        if (!$w) {
            $this->data['container'] = [];
        } else {
            $this->data['w'] = $w;
            if (substr($w, 0, 4) == "TAG:") {
                $w = substr($w, 4);
                $this->data['container'] = M()->all_assoc("SELECT articles.* from tags LEFT JOIN articles on tags.postid=articles.id where tags.title=:title and articles.ison=1  order by top desc,aorder desc,id desc limit 200", [':title' => $w]);
            } elseif (substr($w, 0, 7) == "AUTHOR:") {
                $w = explode(':', substr($w, 7));
                if (count($w) > 1) {
                    $w = $w[0];
                }
                $this->data['container'] = M()->all_assoc("select * from articles where adminuid=:adminuid and ison =1 order by top desc,aorder desc,id desc  limit 200", [':adminuid' => $w]);
            } else {
                $this->data['container'] = M()->all_assoc("select * from articles where title like :title or description like :description  or content like :content and ison =1 order by top desc,aorder desc,id desc  limit 200", [':title' => "%{$w}%", ':description' => "%{$w}%", ':content' => "%{$w}%"]);
            }
//            dump_pre($this->data['container']);
        }


        echo view_plates()->render('blog/search', $this->data);
    }

    public function archive($year = '', $month = '')
    {
        $this->data['current'] = 'archive';
        $year_month = M()->all("SELECT DISTINCT strftime('%Y',datetime(posttime,'unixepoch', 'localtime')) AS `year`,strftime('%m',datetime(posttime,'unixepoch', 'localtime')) AS `month` FROM articles");
        $ym = [];
        foreach ($year_month as $item) {
            $ym[] = $item['year'] . '.' . $item['month'];
        }
        rsort($ym);
        $this->data['ym'] = $ym;

        if (!$year || !$month) {
            if (count($ym)) {
                $this->data['now_ym'] = $ym[0];
            } else {
                $this->data['now_ym'] = time_format(now_stamp(), 'Y.m');;
            }
            $now_arr = explode('.', $this->data['now_ym']);
            $year = $now_arr[0];
            $month = $now_arr[1];
        }
        $year = sprintf("%04d", $year);
        $month = sprintf("%02d", $month);
        $this->data['now_ym'] = $year . '.' . $month;
        $this->data['year'] = $year;
        $this->data['month'] = $month;

        $container = M()->all("SELECT * from articles where strftime('%Y',datetime(posttime,'unixepoch', 'localtime')) ='{$year}' and strftime('%m',datetime(posttime,'unixepoch', 'localtime')) = '{$month}' and ison=1 order by top desc, aorder desc ,id desc");
        $this->data['container'] = $container;
        echo view_plates()->render('blog/archive', $this->data);
    }

    public function notfound()
    {
        $this->data['container'] = '';
        $url=getRequestUri();
        $this->data['err'] = "<b style='color: red'>404，页面：{$url} 未找到</b>";
        echo view_plates()->render('blog/post', $this->data);
    }

    public function post()
    {
        $a = qqq_select_art(27, ['postname' => getGet('postname')], true);
        if (!$a) {
            $a = qqq_select_art(27, ['id' => getGet('id')], true);
        }
        if ($a) {
            $this->data['art'] = $a;
            $this->data['open_article_guestbook'] = $a['openguestbook'];
            $this->data['show_article_guestbook'] = $a['showguestbook'];
            $this->data['message_cout'] = 0;
            $this->data['postmessages'] = [];
            if ($this->data['show_article_guestbook']) {
                $this->data['message_cout'] = [];
                $this->data['postmessages'] = qqq_select_artlist(29, ['postid' => $a['id']], true);
                $this->data['message_cout'] = count($this->data['postmessages']);
            }

            $tag_links = [];
            $tags = tag_find_postid($a['id'], false, 27);
            foreach ($tags as $tag) {
                $tag_links[] = "<a class='btn btn-primary btn-sm btn-min' href='/blog/s-TAG:{$tag['title']}' target='_blank'>{$tag['title']}</a> ";
            }
            $this->data['tags'] = join('', $tag_links);
        } else {
            $this->data['err'] = "<b style='color: red'>404，没有此文章</b>";
        }


        echo view_plates()->render('blog/post', $this->data);
    }

    // post接口，留言功能
    public function guestbook_post($postid, $posturl, $email, $nickname, $message)
    {
        if (!$this->data['open_article_guestbook']) {
            resp_goto_url_message("<div style='text-align: center'><b style='color: rgba(194,0,0,0.75)'>留言功能已关闭！</b></div>", $posturl);
        }

        $a = qqq_select_art(27, ['id' => $postid], true);
        if (!$a) {
            resp_goto_url_message("<div style='text-align: center'><b style='color: rgba(194,0,0,0.75)'>文章不存在！</b></div>", $posturl);
        }
        if ($a['openguestbook']) {
            resp_goto_url_message("<div style='text-align: center'><b style='color: rgba(194,0,0,0.75)'>文章不存在！</b></div>", $posturl);
        }
        if ($a['showguestbook']) {
            resp_goto_url_message("<div style='text-align: center'><b style='color: rgba(194,0,0,0.75)'>文章不存在！</b></div>", $posturl);
        }

        $last_message_time = session_get('last_message_time', 0);
        $c = now_stamp() - $last_message_time;
        if ($c < 30) {
            session_set('email', $email);
            session_set('nickname', $nickname);
            session_set('message', $message);
            resp_goto_url_message("<div style='text-align: center'><b style='color: rgba(194,0,0,0.75)'>请等待{$c}秒后再留言！</b></div>", $posturl);
            exit();
        }
        $ret = qqq_add_art(29, ['postid' => $postid, 'email' => $email, 'nickname' => $nickname, 'message' => $message]);
        if ($ret) {
            session_set('email', $email);
            session_set('nickname', $nickname);
            session_set('message', $message);
            session_set('last_message_time', now_stamp());
            resp_goto_url_message("<div style='text-align: center'><b style='color: #00773d'>留言成功！</b><br>3秒后返回文章页</div>", $posturl, 3);
        }
    }
}
